//
//  JkmMyQrCode.swift
//  SinaWb
//
//  Created by Jiang on 5/22/16.
//  Copyright © 2016 Jiang. All rights reserved.
//

import UIKit
import SnapKit

class JkmMyQrCode: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()
        view.backgroundColor = UIColor.whiteColor()
        navigationItem.title = "我的二维码"
        view.layer.contents = UIImage(named: "MyQrCodebBackgroundImage")?.CGImage
        view.contentMode = .ScaleAspectFill
        let QrCode = UIImageView()
        QrCode.sizeToFit()
        view.addSubview(QrCode)
        QrCode.snp_makeConstraints { (make) in
            make.center.equalTo(view.snp_center)
            make.width.equalTo(view.snp_width).offset(-view.frame.width * 0.5)
            make.height.equalTo(view.snp_width).offset(-view.frame.width * 0.5)
        }        
        //查询滤镜列表
        //        let filterNames = CIFilter.filterNamesInCategory(kCICategoryBuiltIn) as [String]
        //        JkLog(filterNames)
        
        let filter = CIFilter(name: "CIQRCodeGenerator")
        filter?.setDefaults()
        filter?.setValue(ViewModel.sharViewModel.UserInfo?.profile_url!.dataUsingEncoding(NSUTF8StringEncoding), forKey: "inputMessage")
        QrCode.image = createNonInterpolatedUIImageFormCIImage((filter?.outputImage)!, size: 500)
        
        
    }
    /**
     生成高清二维码
     
     - parameter image: 需要生成原始图片
     - parameter size:  生成的二维码的宽高
     */
    private func createNonInterpolatedUIImageFormCIImage(image: CIImage, size: CGFloat) -> UIImage {
        
        let extent: CGRect = CGRectIntegral(image.extent)
        let scale: CGFloat = min(size/CGRectGetWidth(extent), size/CGRectGetHeight(extent))
        
        // 1.创建bitmap;
        let width = CGRectGetWidth(extent) * scale
        let height = CGRectGetHeight(extent) * scale
        let cs: CGColorSpaceRef = CGColorSpaceCreateDeviceGray()!
        let bitmapRef = CGBitmapContextCreate(nil, Int(width), Int(height), 8, 0, cs, 0)!
        
        let context = CIContext(options: nil)
        let bitmapImage: CGImageRef = context.createCGImage(image, fromRect: extent)
        
        CGContextSetInterpolationQuality(bitmapRef,  CGInterpolationQuality.None)
        CGContextScaleCTM(bitmapRef, scale, scale);
        CGContextDrawImage(bitmapRef, extent, bitmapImage);
        
        // 2.保存bitmap到图片
        let scaledImage: CGImageRef = CGBitmapContextCreateImage(bitmapRef)!
        
        return UIImage(CGImage: scaledImage)
    }

}
